package com.xiaoluyy.demo.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger("http_logger");

    /* http连接超时时间 */
    private static final int connectTimeout = 3000;

    /**
     * 发送http请求
     *
     * @param url
     * @param requestObj
     * @return
     */
    public static String doPost(String url, Object requestObj) throws IOException {
        String requestContent = "";
        if (requestObj != null) {
            requestContent = JsonUtil.toJson(requestObj);
        }
        return doPost(url, requestContent);

    }

    /**
     * 发送http请求
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String doPost(String url, String jsonStr) throws IOException {
        HttpPost post = new HttpPost(url);
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).build();
        post.setConfig(config);

        String requestContent = jsonStr;
        if (!StringUtils.isEmpty(requestContent)) {
            HttpEntity entity = new StringEntity(requestContent, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
        }

        logger.info("[HTTP]正在发送http Post请求。。。");
        logger.info("[HTTP]URL-" + url);
        logger.info("[HTTP]BODY:" + requestContent);

        HttpClientBuilder builder = HttpClientBuilder.create();
        try (CloseableHttpClient httpClient = builder.build();
             CloseableHttpResponse response = httpClient.execute(post)) {
            // 执行请求
            HttpEntity httpEntity = response.getEntity();
            String responseStr = EntityUtils.toString(httpEntity);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                logger.info("[HTTP]请求成功。返回数据：" + responseStr);
            } else {
                logger.warn("[HTTP]请求失败。失败原因：" + responseStr);
            }
            return responseStr;
        } catch (ClientProtocolException e) {
            logger.warn("[HTTP]客户端协议异常：" + e.getMessage());
            throw e;
        } catch (IOException e) {
            logger.warn("[HTTP]IO异常:" + e.getMessage());
            throw e;
        }
    }

    /**
     * 发送http请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) throws IOException {
        HttpPost post = new HttpPost(url);
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).build();
        post.setConfig(config);

        String requestContent = "";
        if (params != null && params.size() > 0) {
            requestContent = JsonUtil.toJson(params);
        }
        if (!StringUtils.isEmpty(requestContent)) {
            try {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                NameValuePair pair = new BasicNameValuePair("q", requestContent);
                pairs.add(pair);
                HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
                post.setEntity(entity);
            } catch (UnsupportedEncodingException e) {
                logger.warn("请求数据编码格式不支持：" + e.getMessage());
                throw e;
            }
        }

        HttpClientBuilder builder = HttpClientBuilder.create();
        try (CloseableHttpClient httpClient = builder.build()) {
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity httpEntity = response.getEntity();
            String responseStr = EntityUtils.toString(httpEntity);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                logger.info("请求成功。返回数据：" + responseStr);
            } else {
                logger.warn("请求失败。失败原因：" + responseStr);
            }
            return responseStr;
        } catch (ClientProtocolException e) {
            logger.warn("客户端协议异常：" + e.getMessage());
            throw e;
        } catch (IOException e) {
            logger.warn("IO异常:" + e.getMessage());
            throw e;
        }
    }

}
